package com.xinsilu.hospital.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinsilu.hospital.entity.UserTable;
import com.xinsilu.hospital.mapper.UserTableMapper;
import com.xinsilu.hospital.service.IUserTableService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import java.sql.Wrapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WxLoginController {
    @Autowired
    private IUserTableService iUserTableService;

    @PostMapping("/wxlogin")
    public String wxlogin(HttpServletRequest request){

        // 步骤1：拿到前端传过来的用户信息和code
        String info = request.getParameter("info");
        System.out.println("前端传过来的参数 = " + info);

        JSONObject userInfo = JSON.parseObject(info);
        String code = userInfo.getString("code");

        // 步骤2：调用auth.code2Session接口，获取到openid和session_key
        Map<String, Object> map = getWxUserOpenid(code, "wx6937c31bc7320640", "fa5e4cc3019c427373df33f288c7f094");
        System.out.println("获取到openid和session_key = " + map);

        // 步骤3：处理业务逻辑，通常将openid为用户的唯一标识判断用户是否注册等
        // 将openid作为用户唯一标识登录
        //判断用户openid是否已经存在   存在调用查询方法  不存在调用插入方法
        UserTable user=new UserTable();
        String openid=map.get("openid").toString();

        user.setOpenid(openid);
        Map<String,Object> map1=new HashMap<>();
        map1.put("openid",openid);
        List<UserTable> list = iUserTableService.listByMap(map1);
        if (list.size()==0||null==list){


            boolean c=iUserTableService.save(user);
            if (c){
                System.out.println("插入成功");
            }else {
                System.out.println("系统出现错误");
            }
        }else {
            System.out.println("用户已经存在");
        }



        // 步骤4：返回登录结果到前端
        Map<String,Object> data = new HashMap<>();
        data.put("msg","ok");
        data.put("openid",openid);

        return JSON.toJSONString(data);
    }

    /**
     * 调用auth.code2Session接口，获取openid和获取到openid和session_key
     * @param code          code
     * @param appid         小程序的appid
     * @param appsecret     小程序的appsecret
     * @return
     */
    public static Map<String, Object> getWxUserOpenid(String code, String appid, String appsecret) {
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");//appid设置
        url.append(appid);
        url.append("&secret=");//secret设置
        url.append(appsecret);
        url.append("&js_code=");//code设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        System.out.println("调用auth.code2Session接口 = " + url);
        JSONObject jsonObject = null;
        try {
            CloseableHttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            CloseableHttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            jsonObject = JSON.parseObject(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}